package com.example.a13001.shoppingmalltemplate.fragments;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.View.MarqueeView;
import com.example.a13001.shoppingmalltemplate.activitys.GoodsListActivity;
import com.example.a13001.shoppingmalltemplate.activitys.InformationActivity;
import com.example.a13001.shoppingmalltemplate.activitys.IntegraShopActivity;
import com.example.a13001.shoppingmalltemplate.activitys.SecKillActivity;
import com.example.a13001.shoppingmalltemplate.activitys.WebActivity;
import com.example.a13001.shoppingmalltemplate.adapters.GoodsListRvAdapter;
import com.example.a13001.shoppingmalltemplate.adapters.HomeCouponRvAdapter;
import com.example.a13001.shoppingmalltemplate.adapters.HomePageRvAdapter;
import com.example.a13001.shoppingmalltemplate.adapters.HomePagefGvAdapter;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.modle.Banner;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.GoodsDetail;
import com.example.a13001.shoppingmalltemplate.modle.HomePageTitle;
import com.example.a13001.shoppingmalltemplate.modle.HomepageGoods;
import com.example.a13001.shoppingmalltemplate.modle.NewBanner;
import com.example.a13001.shoppingmalltemplate.modle.News;
import com.example.a13001.shoppingmalltemplate.modle.ShopCouponList;
import com.example.a13001.shoppingmalltemplate.mvpview.NewsView;
import com.example.a13001.shoppingmalltemplate.presenter.HomepagePredenter;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.zph.glpanorama.GLPanorama;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomePageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomePageFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.editText)
    EditText editText;
    Unbinder unbinder;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ConvenientBanner mConvenBanner;
    private List<NewBanner.ListBean> mListBanner = new ArrayList<>();
    private GridView mGvTitle;
    private HomePagefGvAdapter mAdapter;
    private List<HomePageTitle> mListTitle;
    private MarqueeView mMqvHomePage;
    private List<HomepageGoods> mList;
    private HomePageRvAdapter mGoodsListAdapter;
    private ListView mGvHomePageList;
    HomepagePredenter homepagePredenter = new HomepagePredenter(getActivity());
    private static final String TAG = "HomePageFragment";
    private int pageindex = 1;//当前展示页数
    private List<String> groups = new ArrayList<String>();// 组元素数据列表
    private Map<String, List<GoodsDetail.ListBean>> children = new HashMap<String, List<GoodsDetail.ListBean>>();// 子元素数据列表
    int pagesize = 1000000;
    String keyword = "";
    private RecyclerView mRvHome;
    private List<ShopCouponList.ListBean> mListCoupon;
    private HomeCouponRvAdapter mAdapterCoupon;
    private String code;
    private String timeStamp;
    private GLPanorama mVrShow;


    public HomePageFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment HomePageFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomePageFragment newInstance(String param1) {
        HomePageFragment fragment = new HomePageFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(view);
        initData();
        initListener();
        getData();
        return view;
    }

    /**
     * 获取网络数据
     */
    private void getData() {
        //获取资讯列表
        homepagePredenter.getSearchNews(AppConstants.COMPANY_ID, AppConstants.News_ID, keyword, AppConstants.PAGE_SIZE, pageindex);
        //获取轮播图列表
        homepagePredenter.getNewBannerList(AppConstants.COMPANY_ID);
        //获取商品分类列表
        homepagePredenter.getClassifyList(AppConstants.COMPANY_ID, AppConstants.CLASSIFY_ID, pagesize, pageindex);
        //获取优惠券列表
        homepagePredenter.getCouponList(AppConstants.COMPANY_ID, "", "", pagesize, pageindex);
    }

    private NewsView newsView = new NewsView() {
        //资讯列表
        @Override
        public void onSuccess(News mNews) {
            Log.e(TAG, "onSuccess:资讯列表 " + mNews.toString());
            setMarqueeView(mNews);

        }
        //banner列表
        @Override
        public void onSuccessBanner(Banner banner) {
            Log.e(TAG, "onSuccess:banner列表 " + banner.toString());
            int status = banner.getStatus();
//            if (status > 0) {
//                for (int i = 0; i < banner.getFragmentPictureList().size(); i++) {
//
//                    mListBanner.add(AppConstants.INTERNET_HEAD + banner.getFragmentPictureList().get(i).getFragmentPicture());
//                }
//                Log.e(TAG, "onSuccessBanner: " + mListBanner.toString());
//                MyUtils.setConvenientBannerNetWork(mConvenBanner, mListBanner);
//
//
//            } else {
//                Toast.makeText(getActivity(), "" + banner.getReturnMsg(), Toast.LENGTH_SHORT).show();
//            }
        }
        // 获取轮播图
        @Override
        public void onSuccessNewBanner(NewBanner newBanner) {
            Log.e(TAG, "onSuccessNewBanner: "+newBanner );
            int status=newBanner.getStatus();
            if (status>0){
                mListBanner.addAll(newBanner.getList());
//                for (int i = 0; i < newBanner.getList().size(); i++) {
//                    mListBanner.add(AppConstants.INTERNET_HEAD + newBanner.getList().get(i).getPhotoPath());
//                }
                Log.e(TAG, "onSuccessBanner: " + mListBanner.toString());
                MyUtils.setConvenientBannerNetWork2(mConvenBanner, mListBanner);


            }else{

            }
        }

        //商品分类列表
        @Override
        public void onSuccessClassify(GoodsDetail goodsDetail) {
            Log.e(TAG, "onSuccessClassify: " + goodsDetail.toString());
            int states = goodsDetail.getStatus();
            if (states == 1) {

                HashMap<String, ArrayList<GoodsDetail.ListBean>> map = new HashMap<String, ArrayList<GoodsDetail.ListBean>>();
                for (int i = 0; i < goodsDetail.getList().size(); i++) {
                    if (map.containsKey(goodsDetail.getList().get(i).getClassName())) {
                        map.get(goodsDetail.getList().get(i).getClassName()).add(goodsDetail.getList().get(i));
                    } else {
                        ArrayList<GoodsDetail.ListBean> listBeans = new ArrayList<>();
                        listBeans.add(goodsDetail.getList().get(i));
                        map.put(goodsDetail.getList().get(i).getClassName(), listBeans);
                    }
                }

                Set set = map.keySet();
                Iterator iterator = set.iterator();
                for (int i = 0; i < map.size(); i++) {
                    iterator.hasNext();
                    String s = iterator.next().toString();
                    Log.e("aaa", "------>" + s);
                    List<GoodsDetail.ListBean> goods = new ArrayList<>();
                    goods = map.get(s);
                    HomepageGoods homepageGoods = new HomepageGoods(s, goods);
                    mList.add(homepageGoods);
                }
                Log.e("aaa", "------>" + map.toString());
                mGoodsListAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(getActivity(), "" + goodsDetail.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }

        }

        //获取优惠券列表
        @Override
        public void onSuccessGetCouponList(ShopCouponList shopCouponList) {
            Log.e(TAG, "onSuccessGetCouponList: " + shopCouponList.toString());
            int status = shopCouponList.getStatus();
            if (status > 0) {
                mListCoupon.addAll(shopCouponList.getList());
                mAdapterCoupon.notifyDataSetChanged();
            } else {
                Toast.makeText(getActivity(), "" + shopCouponList.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        //   领取优惠券
        @Override
        public void onSuccessObtainCoupon(CommonResult commonResult) {
            Log.e(TAG, "onSuccessObtainCoupon: " + commonResult.toString());
            int status = commonResult.getStatus();
            if (status > 0) {
                Toast.makeText(getActivity(), "优惠券领取成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), "" + commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError: " + result.toString());
        }
    };

    /**
     * 初始化事件监听
     */
    private void initListener() {
        // 资讯点击
        mMqvHomePage.setOnClick(new MarqueeView.OnClick() {
            @Override
            public void onClick() {
                startActivity(new Intent(getActivity(), InformationActivity.class));
            }
        });
        //优惠券点击
        mAdapterCoupon.setOnItemClickListener(new GoodsListRvAdapter.onItemClickListener() {
            @Override
            public void onClick(int position) {
                homepagePredenter.obTainCoupon(AppConstants.COMPANY_ID, code, timeStamp, mListCoupon.get(position).getAid());
            }
        });
        //轮播图点击
        mConvenBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int photoConType = mListBanner.get(position).getPhotoConType();//图片详情类型 0 无详情页 1 跳转链接 2 自定义详情页
                if (photoConType==1||photoConType==2){
                    Intent intent=new Intent(getActivity(), WebActivity.class);
                    intent.putExtra("url",mListBanner.get(position).getPhotoLink());
                    intent.putExtra("name",mListBanner.get(position).getPhotoName());
                    startActivity(intent);
                }
            }
        });

    }

    /**
     * 初始化数据源
     */
    private void initData() {
        homepagePredenter.onCreate();
        homepagePredenter.attachView(newsView);

        String safetyCode = MyUtils.getMetaValue(getActivity(), "safetyCode");
        code = Utils.md5(safetyCode + Utils.getTimeStamp());
        timeStamp = Utils.getTimeStamp();

        mList = new ArrayList<>();
        mGoodsListAdapter = new HomePageRvAdapter(getActivity(), mList);


        mListCoupon = new ArrayList<>();
        mAdapterCoupon = new HomeCouponRvAdapter(getActivity(), mListCoupon);
        mRvHome.setAdapter(mAdapterCoupon);

        mGvHomePageList.setAdapter(mGoodsListAdapter);

        mListTitle = new ArrayList<>();
        mListTitle.add(new HomePageTitle(R.drawable.recommend, "推荐商品"));
        mListTitle.add(new HomePageTitle(R.drawable.gift, "新品上架"));
        mListTitle.add(new HomePageTitle(R.drawable.sales_rank, "促销秒杀"));
        mListTitle.add(new HomePageTitle(R.drawable.seckill, "积分商城"));

        mAdapter = new HomePagefGvAdapter(getActivity(), mListTitle);
        mGvTitle.setAdapter(mAdapter);
        mGvTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    //推荐商品
                    case 0:
                        startActivity(new Intent(getActivity(), GoodsListActivity.class).putExtra("elite", AppConstants.ELITE_YES).putExtra("searchword", ""));
                        break;
                    //新品上架
                    case 1:
                        startActivity(new Intent(getActivity(), GoodsListActivity.class).putExtra("xinpin", AppConstants.XINPIN_YES).putExtra("searchword", ""));
                        break;
                    //促销秒杀
                    case 2:
                        startActivity(new Intent(getActivity(), SecKillActivity.class));
                        break;
                    //积分商城
                    case 3:
                        startActivity(new Intent(getActivity(), IntegraShopActivity.class));
                        break;
                }
            }
        });

        //搜索

        editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //判断是否是“完成”键
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = editText.getText().toString().trim();
                    startActivity(new Intent(getActivity(), GoodsListActivity.class).putExtra("searchword", keyword));
//                    KeyboardUtils.hideSoftInput(getActivity());
//                    //隐藏软键盘
//                    InputMethodManager imm = (InputMethodManager) v
//                            .getContext().getSystemService(
//                                    Context.INPUT_METHOD_SERVICE);
//                    if (imm.isActive()) {
//                        imm.hideSoftInputFromWindow(
//                                v.getApplicationWindowToken(), 0);
//                    }
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {


        mGvHomePageList = (ListView) view.findViewById(R.id.gv_homepage_list);
//        View  mHeadViewOne= LayoutInflater.from(getActivity()).inflate(R.layout.include_search,null);
        View mHeadViewTwo = LayoutInflater.from(getActivity()).inflate(R.layout.include_headerview_banner, null);
        View mHeadViewThree = LayoutInflater.from(getActivity()).inflate(R.layout.include_homepage_type, null);
        View mHeadViewFour = LayoutInflater.from(getActivity()).inflate(R.layout.include_marqueview, null);
        View mCouponView = LayoutInflater.from(getActivity()).inflate(R.layout.include_recyclerview, null);
        View vrView = LayoutInflater.from(getActivity()).inflate(R.layout.include_vr, null);
//        mGvHomePageList.addHeaderView(mHeadViewOne);
        mGvHomePageList.addHeaderView(mHeadViewTwo);
        mGvHomePageList.addHeaderView(mHeadViewThree);
        mGvHomePageList.addHeaderView(mHeadViewFour);
        mGvHomePageList.addHeaderView(vrView);
        mGvHomePageList.addHeaderView(mCouponView);

        mConvenBanner = (ConvenientBanner) mHeadViewTwo.findViewById(R.id.cb_homepage);
        mGvTitle = (GridView) mHeadViewThree.findViewById(R.id.gv_homepage);
        mMqvHomePage = (MarqueeView) mHeadViewFour.findViewById(R.id.mqv_homepage);
        mRvHome = (RecyclerView) mCouponView.findViewById(R.id.rv_home);
        mVrShow = (GLPanorama) vrView.findViewById(R.id.mGLPanorama);
//        mEtSearch = (EditText) mHeadViewOne.findViewById(R.id.editText);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvHome.setLayoutManager(linearLayoutManager);
        mVrShow.setGLPanorama(R.drawable.imggugong);
    }

    //垂直跑马
    private void setMarqueeView(News mNews) {
        List<News.ListBean> marquees = new ArrayList<>();
        marquees.addAll(mNews.getList());
        mMqvHomePage.startWithList(marquees);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
